<?php
/**
 * Model class link to table transactions in database
 *
 * @author Dat Nguyen <datn@evolable.asia>
 */
class Transaction extends AppModel {
	var $name = 'Transaction';
	var $useTable = 'transactions';
	var $primaryKey = 'id';

	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => array(
				'User.del_flg' => 0,
			)
		),
		'CourseDetail' => array(
			'className' => 'CourseDetail',
			'foreignKey' => 'detail_id',
			'conditions' => array(
				'CourseDetail.del_flg' => 0,
				)
		),
		'PaymentMethod' => array(
			'className' => 'PaymentMethod',
			'foreignKey' => 'payment_id'
		),
	);

	/**
	 * Get transaction by token
	 *
	 * @param $token
	 * @return mixed
	 */
	function getTransactionByToken($token) {
		$options = array();
		$options['conditions'] = array(
			'token' => $token,
		);

		$options['fields'] = array(
			$this->alias.'.*',
		);

		return $this->find('first', $options);
	}
	/**
	 * Get all transaction of a course detail
	 * @param $detailId
	 */
	function getTransactionOfDetail($detailId, $optionsOnly = false, $options = array()) {
		$defaultOptions = array();
		$defaultOptions['conditions'] = array(
			$this->alias . '.del_flg' => 0,
			$this->alias . '.detail_id' => $detailId,
		);
		$defaultOptions['joins'] = array(
			array(
				'table' => 'profiles',
				'alias' => 'Profile',
				'type' => 'LEFT',
				'conditions' => array(
					'Transaction.user_id = Profile.user_id AND Profile.del_flg = 0'
				)
			)
		);
		$defaultOptions['fields'] = array(
			$this->alias . '.*',
			'Profile.first_name',
			'Profile.last_name',
			$this->PaymentMethod->alias . '.payment_method',
		);
		$defaultOptions = array_merge($defaultOptions, $options);
		if ($optionsOnly) {
			return $defaultOptions;
		}
		return $this->find('all', $defaultOptions);
	}

	/**
	 * Mass update del_flg of transaction table base on id
	 *
	 * @param $id
	 * @param $value
	 */
	function updateDeleteFlg($id, $value) {
		if (!is_array($id)) {
			$id = array($id);
		}
		if ($value != 0) {
			$value = 1;
		}
		App::import('model', 'EnteredCourse');
		$enterCourse = new EnteredCourse();
		$conditions = array(
			$this->alias . '.id' => $id,
		);
		$this->updateAll(array('del_flg' => $value), $conditions);
		$conditions = array(
			$enterCourse->alias . '.detail_id IN (SELECT detail_id FROM transactions WHERE id IN ('.implode(',', $id).'))',
		);
		$enterCourse->updateAll(array('del_flg' => $value), $conditions);
	}

	/**
	 * Mass update status of transaction base on id
	 * @param $id
	 * @param $value
	 */
	function updateStatusFlg($id, $value) {
		if (!is_array($id)) {
			$id = array($id);
		}
		if ($value != 0) {
			$value = 1;
		}
		$conditions = array(
			$this->alias . '.id' => $id,
		);
		$this->updateAll(array('status' => $value), $conditions);

		$options = array();
		$options['conditions'] = array(
			$this->alias . '.id' => $id,
		);
		$options['fields'] = array(
			$this->alias . '.user_id',
			$this->alias . '.detail_id',
			$this->alias . '.id',
			$this->alias . '.amount',
			$this->alias . '.del_flg',
		);
		$transactions = $this->find('all', $options);
		App::import('model', 'EnteredCourse');
		App::import('model', 'User');
		$user = new User();
		$ratio = Configure::read('point_ratio');
		$enterCourse = new EnteredCourse();
		if ($value == 0) {
			$enterCourse->deleteAll(array(
				'transaction_id' => $id,
			));
			//update user point
			foreach ($transactions as $t) {
				$user->removePoint($t['Transaction']['user_id'], $t['Transaction']['amount'], $ratio);
			}
		} else {
			foreach ($transactions as $t) {
				$options = array();
				$options['conditions'] = array(
					'detail_id' => $t['Transaction']['detail_id'],
					'user_id' => $t['Transaction']['user_id'],
					'transaction_id' => $t['Transaction']['id'],
				);
				$count = $enterCourse->find('count', $options);
				if ($count > 0) {
					continue;
				}
				$data = array(
					'id' => null,
					'detail_id' => $t['Transaction']['detail_id'],
					'user_id' => $t['Transaction']['user_id'],
					'transaction_id' => $t['Transaction']['id'],
					'del_flg' => $t['Transaction']['del_flg'],
				);
				$user->removePoint($t['Transaction']['user_id'], $t['Transaction']['amount'], $ratio);
				$enterCourse->save($data);
			}
		}
	}

	/**
	 * Add transaction to database, before adding, checking transaction is existing or not
	 * @param $transaction
	 * @return mixed
	 */
	function addTransaction($transaction) {
		$default = array(
			'detail_id' => null,
			'user_id' => null,
			'payment_id' => null,
			'amount' => 0,
			'status' => 0,
			'token' => '',
		);
		$data = array_merge($default, $transaction);
		$options = array();
		$options['conditions'] = array(
			$this->alias.'.del_flg' => 0,
			$this->alias.'.token' => $data['token'],
		);
		if ($transaction = $this->find('first', $options)) {
			$this->log('Transaction existing in database, find option ' . json_encode($options), 'error');
		}

		return $this->save($data);
	}

	/**
	 * Get transactions of user, if want more data, could add options parameter
	 * @param $userId
	 * @param array $options Reference to condition of find function of model
	 * @param boolean $getOption If true, return the options of find only, else return result of find
	 */
	function getUserTransaction($userId, $options = array(), $getOption = false) {
		$default = array();
		$default['fields'] = array(
			$this->alias . '.*',
			$this->PaymentMethod->alias . '.payment_method',
		);
		$default['conditions'] = array(
			$this->alias . '.del_flg' => 0,
		);
		$options = array_merge($default, $options);
		$options['conditions'][$this->alias.'.user_id'] = $userId;

		if ($getOption) {
			return $options;
		}

		return $this->find('all', $options);
	}
	
	function getNumberOfUserTransactionByStatus($userId, $status) {
		return $this->find('count', array(
			'conditions' => array(
				$this->alias . '.user_id' => $userId,
				$this->alias . '.status' => $status,
				$this->alias . '.del_flg' => 0
			)
		));
	}
}